from django import forms
from django.core.validators import RegexValidator

from appdemo.models import UserInfo


class MyRegForm(forms.Form):
    username = forms.CharField(label='用户名', min_length=3, max_length=8,
                               error_messages={
                                   'min_length': '用户名最少3位',
                                   'max_length': '用户名最大8位',
                                   'required': '用户名不能为空'
                               },
                               widget=forms.TextInput(attrs={'class': 'form-control'}))
    password = forms.CharField(label='密码', min_length=3, max_length=8,
                               error_messages={
                                   'min_length': '密码最少3位',
                                   'max_length': '密码最大8位',
                                   'required': '密码不能为空'
                               },
                               widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    re_password = forms.CharField(label='确认密码', min_length=3, max_length=8,
                                  error_messages={
                                      'min_length': '确认密码最少3位',
                                      'max_length': '确认密码最大8位',
                                      'required': '确认密码不能为空'
                                  },
                                  widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(label='邮箱',
                             error_messages={
                                 'required': '邮箱不能为空',
                                 'invalid': '邮箱格式不正确'
                             },
                             widget=forms.EmailInput(attrs={'class': 'form-control'}))
    phone = forms.CharField(label='手机号',
                            validators=[
                                RegexValidator(r'\d+', '请输入数字'),
                                RegexValidator(r'^1[3-9]\d{9}', '请输入正确的手机号'),
                            ],
                            widget=forms.NumberInput(attrs={'class': 'form-control'}))

    # 局部钩子: 校验用户名是否存在
    def clean_username(self):
        username = self.cleaned_data.get('username')
        # 去数据库中校验
        is_exist = UserInfo.objects.filter(username=username)
        if is_exist:
            # 添加报错信息
            self.add_error('username', '用户名已存在')
        return username

        # 全局钩子: 判断两次密码是否一致

    def clean(self):
        password = self.cleaned_data.get('password')
        re_password = self.cleaned_data.get('re_password')
        # 判断两次密码是否一致
        if password != re_password:
            # 添加报错信息
            self.add_error('re_password', '两次密码不一致')
        return self.cleaned_data